//
//  MainViewController.swift
//  Weibo
//
//  Created by apple on 15/12/6.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    //MARK 监听方法
    @objc private func clickComposedButton() {
        
        //1 判断用户是否登录
        let vc = UserAccountViewModel.sharedUserAccount.userLogon ? ComposeViewController() : OAuthViewController()
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)
        
        
    }
    //MARK 试图声明周期函数
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加控制器  并不会创建tabbar中间的按钮
        //懒加载是无处不在的 所有控件都是延迟加载
        addChildViewControllers()
        
        setupComposedButton()
    }
    override func viewWillAppear(animated: Bool) {
        //会创建tabBar中的所有控制器对应的按钮
        super.viewWillAppear(animated)
        
        //将按钮弄到最前面
        tabBar.bringSubviewToFront(composedButton)
        
    }
    
    //MARK:懒加载控件
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
    
}


//MARK: 设置界面
extension MainViewController {
    ///设置撰写按钮
    private func setupComposedButton() {
    
        // 1 添加按钮
        tabBar.addSubview(composedButton)
        // 2 调整按钮
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        // 3 添加监听方法
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
    }

    private func addChildViewControllers() {
        //设置不被渲染
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
         addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
         addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
         addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
     
        
    }
    
    //添加控制器
    
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        //设置标题
        vc.title = title
        
        //设置图片
        vc.tabBarItem.image = UIImage(named: imageName)
        
        //设置跟控制器
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}



